package com.yys.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yys.common.constant.ProductConstant;
import com.yys.common.to.SkuReductionTo;
import com.yys.common.to.SpuBoundTo;
import com.yys.common.to.es.SkuEsTo;
import com.yys.common.to.es.SkuHasStockTo;
import com.yys.common.utils.R;
import com.yys.gulimall.product.entity.*;
import com.yys.gulimall.product.feign.CouponFeignService;
import com.yys.gulimall.product.feign.SearchFeignService;
import com.yys.gulimall.product.feign.WareFeignService;
import com.yys.gulimall.product.service.*;
import com.yys.gulimall.product.vo.sku.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yys.common.utils.PageUtils;
import com.yys.common.utils.Query;

import com.yys.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;


    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //TODO 后面完善 分布式事务,熔断,降级等
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        //保存基本数据 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        BeanUtils.copyProperties(spuInfo,spuInfoEntity);

        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.saveBaseSpuInfo(spuInfoEntity);

        // 保存spu描述图片 pms_spu_info_desc
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuinfoDesc(descEntity);

        // 保存spu图片集 pms_spu_images
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();

        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        // 保存spu的积分信息 gulimall_sms -> sms_spu_bounds
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());

        R couponBoundsRes = couponFeignService.saveSpuBounds(spuBoundTo);
        if(couponBoundsRes.getCode() != 0) {
            log.error("远程保存SPU积分信息失败");
        }

        // 保存spu的所有sku信息
        List<Skus> skus = spuInfo.getSkus();

        if(ObjectUtils.isNotEmpty(skus)) {
            skus.forEach(item -> {
                String defaultImg = "";
                for(Images img : item.getImages()) {
                    if(img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                // sku 基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                // sku 图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                // TODO 没有图片路径的无需保存
                skuImagesService.saveBatch(skuImagesEntities);

                // sku 的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(m -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(m, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // sku 的优惠 满减信息: 远程调用 gulimall_sms -> sms_sku_ladder\sms_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 满0元打0折的数据不需要保存
                // ps注意这里要用BigDecimal("0") -> 这个0要带引号,不带引号不能保证结果是精确的0
//                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R couponRedctionRes = couponFeignService.saveSkuRedction(skuReductionTo);
                    if(couponRedctionRes.getCode() != 0) {
                        log.error("远程保存SKU满减信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        /**
         * status , key , brandId , catelogId
         * */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("id",key).or().like("spu_name",key));
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id",catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        ArrayList<SkuEsTo> list = new ArrayList<>();
        // 组装数据
        // 查出所有spuId对应的sku信息,品牌和名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        //TODO 查询所有可以被检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.getSearchAttrs(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsTo.Attrs> attrsList = productAttrValueEntities.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsTo.Attrs attrs = new SkuEsTo.Attrs();
                    BeanUtils.copyProperties(item,attrs);
                    return attrs;
                })
                .collect(Collectors.toList());

        //TODO 远程调用库存系统查询是否有库存 一次性查出
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        Map<Long, Boolean> hasStockMap = null;
        try {
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>() {};
            hasStockMap = skusHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常:",e);
        }



        // 封装sku的信息
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsTo> skuEsToList = skuInfoEntities.stream().map(sku -> {
            SkuEsTo skuEsTo = new SkuEsTo();
            BeanUtils.copyProperties(sku,skuEsTo);
            skuEsTo.setSkuPrice(sku.getPrice());
            skuEsTo.setSkuImg(sku.getSkuDefaultImg());
            // hasStock
            //TODO 远程调用库存系统查询是否有库存
            // 这里希望库存系统可以给一个全文查询结果,而不是遍历调用一遍一遍判断是否有库存
            if(ObjectUtils.isNotEmpty(finalHasStockMap)) {
                skuEsTo.setHasStock(finalHasStockMap.get(skuEsTo.getSkuId()));
            } else {
                skuEsTo.setHasStock(true);
            }

            // TODO 热度评分 先默认放0
            skuEsTo.setHotScore(0L);
            // TODO 查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(skuEsTo.getBrandId());
            skuEsTo.setBrandName(brandEntity.getName());
            skuEsTo.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(skuEsTo.getCatalogId());
            skuEsTo.setCatalogName(categoryEntity.getName());

            // 设置检索属性attrs
            skuEsTo.setAttrs(attrsList);
            return skuEsTo;
        }).collect(Collectors.toList());

        //TODO 将数据发给es: gulimall-search
        R r = searchFeignService.productStatusUp(skuEsToList);
        if(r.getCode() == 0) {
            //TODO 修改发布状态
            // TODO 重复调用 接口幂等性
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 调用失败
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        return this.getById(skuInfoEntity.getSpuId());
    }


}